
// 获取购物车
(function(){
	let oCartContent = document.querySelector('.cart-content');
	let oTable = document.querySelector('.cart-content table');
	let oNowSettlementBtn = document.querySelector('.now-settlement-btn');
	
	// 验证一下
	if(!localStorage.getItem('token') || !localStorage.getItem('username')){
		alert('非法登录');
		return;
	};
	
	wj.ajax({
		method: 'post',
		url: BASE_URL + '/api_cart',
		data: {status: 'viewcart', userId: localStorage.getItem('token')},
		success(res){
			console.log(res);
			if(res.code != 0){
				console.log(res);
				return;
			};
			
			//组装DOM
			let goodsArr = res.data;
			// 验证
			if(goodsArr.length == 0){
				oCartContent.innerHTML = '暂无商品...';
				return;
			};
			
			// 结构
			let str = `
				<tr>
					<td><input type="checkbox" class="check-all" />全选</td>
					<td>良品</td>
					<td>数量</td>
					<td>单价</td>
					<td>小计</td>
					<td>神操作</td>
				</tr>
			`;
			
			// 遍历
			goodsArr.forEach(item => {
				str += `
					<tr>
						<td>
							<input type="checkbox" class="check"  goods-id="${item.goods_id}"/>
							<img src="${item.goods_thumb}" alt="" />
						</td>
						<td>${item.goods_name}</td>
						<td>
							<span class="reduce" goods-id="${item.goods_id}" price="${item.price}">-</span>
							<span class="num">${item.goods_number}</span>
							<span class="add" goods-id="${item.goods_id}" price="${item.price}">+</span>
						</td>
						<td>${item.price}</td>
						<td>${item.price * item.goods_number}</td>
						<td>
							<a href="javascript:;" class="del-btn" goods-id="${item.goods_id}">删除</a>
						</td>
					</tr>
				`;
			});
			
			// 添加到页面
			oTable.innerHTML = str;
			
			// 给整个表格添加点击事件
			oTable.onclick = function(event){
				// 获取类名
				let clsName = event.target.className;
				
				// 验证
				// 点击全选
				if(clsName == 'check-all'){
					// 获取页面中所有单个商品
					let aCheck = document.querySelectorAll('.cart-content .check');
					console.log(event.target.checked);
					
					aCheck.forEach(item => {
						item.checked = event.target.checked;
						// 添加标记
						item.setAttribute('check', event.target.checked ? 'checked' : '');
					});
					
					// 调用总价方法
					getPriceAll();
					
				};
				
				// 点击单选
				if(clsName == 'check'){
					// console.log(event.target.checked);
					// 添加标记
					event.target.setAttribute('check', event.target.checked ? 'checked' : '');
					// 调用总价方法
					getPriceAll();
				};
				
				// 点击减 加
				if(clsName == 'reduce' || clsName == 'add'){
					
					let num = null;
					let numDom = null;
					let subtotalDom = event.target.parentNode.nextElementSibling.nextElementSibling;
					
					if(clsName == 'reduce'){
						
						numDom = event.target.nextElementSibling;
						num = parseInt(event.target.nextElementSibling.innerHTML);
						num--;
						num = num <= 1 ? 1 : num;
						
					}else if(clsName == 'add'){
						
						numDom = event.target.previousElementSibling;
						num = parseInt(event.target.previousElementSibling.innerHTML);
						num++;
						num = num >= 10 ? 10 : num;
						
					}

					//更新后台数据
					wj.ajax({
						method: 'post',
						url: BASE_URL + '/api_cart',
						data: {
							status: 'addcart', 
							userId: localStorage.getItem('token'),
							goodsId: event.target.getAttribute('goods-id'),
							goodsNumber: num
						},
						success(res){
							// console.log(res);
							if(res.code != 0){
								console.log(res);
								return;
							};
							// 更新DOM
							numDom.innerHTML = num;
							subtotalDom.innerHTML = num * parseFloat(event.target.getAttribute('price'));
							// 调用总价
							getPriceAll();
						},
					});
				};
		
				// 点击删除
				if(clsName == 'del-btn'){
					// 删除后台数据
					wj.ajax({
						method: 'post',
						url: BASE_URL + '/api_cart',
						data: {
							status: 'delcart', 
							userId: localStorage.getItem('token'),
							goodsId: event.target.getAttribute('goods-id')
						},
						success(res){
							// console.log(res);
							if(res.code != 0){
								console.log(res);
								return;
							};
							// 更新DOM
							event.target.parentNode.parentNode.remove();
							// 调用总价
							getPriceAll();
						},
					});
				};			
			};
			
			//总价方法
			function getPriceAll(){
				// 选到所有 check="checked" 证明被选中
				let aCheckAll = document.querySelectorAll('[check="checked"]');
				let oPriceAllDom = document.querySelector('.price-all');
				let priceAll = 0;
				aCheckAll.forEach(item => {
					let numDom = item.parentNode.nextElementSibling.nextElementSibling.children[1];
					let priceDom = item.parentNode.nextElementSibling.nextElementSibling.nextElementSibling;
					let num = parseFloat(numDom.innerHTML);
					let price = parseFloat(priceDom.innerHTML);
					priceAll += num * price;
				});
				// 设置
				oPriceAllDom.innerHTML = '总价:' + priceAll;
			};
			
			
			// 点击立即结算按钮
			oNowSettlementBtn.onclick = function(){
				//要拿到所有被选中的元素 规定：data-goods="check" data-goods=""
				let aCheckDom = document.querySelectorAll('[check="checked"]');
				console.log(aCheckDom)
				// 验证
				if(aCheckDom.length == 0){
					alert('请选择商品');
					return;
				};
				
				let goodsIdArr = [];
				aCheckDom.forEach(item => {
					goodsIdArr.push(item.getAttribute('goods-id'));
				});
				let goodsId = goodsIdArr.join('&');
				console.log(goodsIdArr);
				console.log(goodsId);
				// 请求加入结算
				wj.ajax({
					method: 'post',
					url: BASE_URL + '/api_settlement',
					data: {
						status : 'addsettlement',
						userId : TOKEN,
						from : 'cart',
						goodsId: goodsId,
					},
					success(res){
							console.log(res);
							if(res.code != 0){
								console.log(res);
								return;
							};
							
							//跳转到地址页面
							location.href = 'address.html';
					}
				})
				
			};
			
		}
		
	})
	
})();